'use client'

import { useState, useEffect, useRef } from 'react'
import api from '@/lib/api'

interface CountdownTimerProps {
  createdAt: string
  expiresAt: string
  orderId: number
  onTimeout: () => void
}

export default function CountdownTimer({ createdAt, expiresAt, orderId, onTimeout }: CountdownTimerProps) {
  const [timeLeft, setTimeLeft] = useState<string>('')
  const timerRef = useRef<NodeJS.Timeout>()
  const hasTimedOut = useRef(false)

  useEffect(() => {
    const calculateTimeLeft = () => {
      try {
        const now = new Date()
        const [datePart, timePart] = expiresAt.split(' ')
        const [year, month, day] = datePart.split('-').map(Number)
        const [hrs, mins, secs] = timePart.split(':').map(Number)
        
        const expireTime = new Date(year, month - 1, day, hrs, mins, secs)
        
        if (isNaN(expireTime.getTime())) {
          console.error('Invalid expiration date:', expiresAt)
          return '时间格式错误'
        }

        const difference = expireTime.getTime() - now.getTime()

        if (difference <= 0) {
          if (timerRef.current) {
            clearInterval(timerRef.current)
          }
          // 如果还没有处理过超时
          if (!hasTimedOut.current) {
            hasTimedOut.current = true
            // 调用超时处理函数
            onTimeout()
          }
          return '已超时'
        }

        const totalSeconds = Math.floor(difference / 1000)
        const minutes = Math.floor(totalSeconds / 60)
        const seconds = totalSeconds % 60
        
        const formattedMinutes = String(minutes).padStart(2, '0')
        const formattedSeconds = String(seconds).padStart(2, '0')
        
        return `${formattedMinutes}:${formattedSeconds}`
      } catch (error) {
        console.error('Error calculating time left:', error)
        return '计算错误'
      }
    }

    setTimeLeft(calculateTimeLeft())

    timerRef.current = setInterval(() => {
      setTimeLeft(calculateTimeLeft())
    }, 1000)

    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current)
      }
    }
  }, [expiresAt, onTimeout])

  return (
    <div className="text-sm text-orange-500">
      {timeLeft === '已超时' ? (
        <span className="text-red-500">支付已超时</span>
      ) : (
        `支付倒计时：${timeLeft}`
      )}
    </div>
  )
} 